<?php
/**
 * Home_Controller
 * - Controller for module page Home
 * @author ANHTAM
 * @since 1.1 - Sep 27, 2011
 * $Id: $
 */
// Require module for controller

require_once(LIB_DAO_DIR . "/MUser.class.php");
require_once(LIB_DAO_DIR . "/GioHang.class.php");
require_once(LIB_DAO_DIR . "/DonHang.class.php");

class Home_Controller extends ControllerAdmin {
	/**
     * - Constructor
     */
    public function __construct() {
    	parent::__construct();
    }
    
    /**
     * actionIndex
     * - page index of controller
     */
    public function actionIndex() {
    	
    	// Process init
        $objView = new ViewAdmin ();
        $this->tpl_title = 'Thống kê';
        $this->ArSanPham = array();
        $ojbSanPham = new MSanpham();
        $ojbKhoHang = new KhoHang();
        $dataGet = FunctionCommon::getGet(array('danhmucid', 'iddm', 'subiddm', 'sort', 'value'));
        $nameSort = ($dataGet['sort'] != '' && $dataGet['sort'] != 'soluong') ? $dataGet['sort'] : 's.seq';
        $this->valueSort = ($dataGet['value'] != '') ? $dataGet['value'] : 'DESC';
        // Get from table danhmuc
        $ojbDanhMuc = new DanhMuc();
        $danhMucArray = $ojbDanhMuc->getAllByAttribute(array());
        $this->danhMucA = $this->converSelect($danhMucArray);
        if ($dataGet['danhmucid'] != '') {
        	$this->danhmucid = $dataGet['danhmucid'];
        	Session::Set("danhmucid", $this->danhmucid);
        }
        $this->danhmucid = (Session::Get("danhmucid") != '') ? Session::Get("danhmucid") : '1';
        
        // Get from table category
        $ojbCategory = new SanphamCategory();
        $categoryArray = $ojbCategory->getAllByAttribute(array("danhmuc_id"=>array("math"=>"=", "value"=>$this->danhmucid)), array("id", "name"));
        $count1 = count($categoryArray);
        $this->categoryA = $this->converSelect($categoryArray);
        $this->iddm = $dataGet['iddm'];
        
        // Get from table scategory
        $ojbSCategory = new SanphamSCategory();
        $subCateArray = $ojbSCategory->getAllByAttribute(array("danhmuc_id"=>array("math"=>"=", "value"=>$this->danhmucid), "iddm"=>array("math"=>"=", "value"=>$this->iddm)), array("id", "iddm", "name"));
        $count2 = count($subCateArray);
        $this->sCategoryA = $this->converSelect($subCateArray);
        $this->subiddm = $dataGet['subiddm'];
        
        // Get from table sanpham
        $ojbSanPham = new MSanpham();
        $confiden = array();
        if ($this->danhmucid != '') {
        	$confiden = array("s.danhmuc_id"=>array("math"=>"=", "value"=>$this->danhmucid));
        } 
        if ($this->danhmucid != '' && $this->iddm != '') {
        	$confiden = array("s.danhmuc_id"=>array("math"=>"=", "value"=>$this->danhmucid), "s.iddm"=>array("math"=>"=", "value"=>$this->iddm));
        }
        if ($this->danhmucid != '' && $this->iddm != '' && $this->subiddm != '') {
        	$confiden = array("s.danhmuc_id"=>array("math"=>"=", "value"=>$this->danhmucid), "s.iddm"=>array("math"=>"=", "value"=>$this->iddm), "s.iddmc"=>array("math"=>"=", "value"=>$this->subiddm));
        }
        $field = "d.name as nameD, c.name as nameC, s.id, s.danhmuc_id, s.iddm, s.iddmc, s.name as nameS, s.soluong";
        $sanPhamArray = $ojbSanPham->sanPhamHome($confiden, $field, $nameSort, $this->valueSort);
        foreach ($sanPhamArray as $idSP) {
        	if ($idSP['danhmuc_id'] == '1') {
        		$idSP['soluong'] = $ojbKhoHang->totalSanPham($idSP['id']);
        	}
        	$this->ArSanPham[] = $idSP;
        }
        
        if ($dataGet['sort'] == 'soluong') {
        	$this->ArSanPham = $this->sortData($this->ArSanPham, $this->valueSort);
        }
        
        // Process view
        $objView->assignobj($this);
        $objView->display();
    }
    
    public function sortData($arrS, $type) {
    	$tc = count ($arrS);
    	if ($type == 'DESC') {
    		for ($i=0; $i < $tc; $i++) {
    			for ($j = $i+1; $j < $tc; $j++) {
    				if ($arrS[$i]['soluong'] > $arrS[$j]['soluong']) {
    					$dc = $arrS[$j];
    					$arrS[$j] = $arrS[$i];
    					$arrS[$i] = $dc;
    				}
    			}
    		}
    	}
    	if ($type == 'ASC') {
    		for ($i=0; $i < $tc; $i++) {
    			for ($j = $i+1; $j < $tc; $j++) {
    				if ($arrS[$i]['soluong'] < $arrS[$j]['soluong']) {
    					$dc = $arrS[$j];
    					$arrS[$j] = $arrS[$i];
    					$arrS[$i] = $dc;
    				}
    			}
    		}
    	}
    	return $arrS;
    }
    
	public function converSelect($arrChosse, $id = "", $value = "") {
    	$resultA = array();
    	if(is_array($arrChosse) && !empty($arrChosse)) {
    		foreach ($arrChosse as $val) {
    			if ($id != "") {
    				$resultA[$val[$id]] = $val[$value];
    			} else {
    				$resultA[$val['id']] = $val['name'];
    			}
    		}
    	}
    	return $resultA;
    }
    
	/**
     * actionAdmin
     * - page admin of controller
     */
    public function actionAdmin() {
    	
    	// Process init
        $objView = new ViewAdmin ();
        $this->tpl_title = 'demo model';
       
        
        // Process view
        $objView->assignobj($this);
        $objView->display();
    }
    
	/**
     * actionDonhang
     * - page admin of controller
     */
    public function actionDonhang() {
    	
    	// Process init
        $objView = new ViewAdmin ();
        $this->tpl_title = 'QUẢN LÝ ĐƠN HÀNG';
        $this->flagMenuDonHang = true;
        $this->tpl_title_list = "QUẢN LÝ ĐƠN HÀNG";
        $this->arrContent = array();
		$this->currPage = '';
		$this->numberPage = '';
		$this->strPaging = '';
        
    	if (!$this->loginFlag || $this->dataUser['quyen'] > '2') {
        	FunctionCommon::sendRedirect();
        }
        
        $this->getGet = FunctionCommon::getGet(array('type'));
        $this->getPost = array("maHang"=>"", "dateStart"=>"", "dateEnd"=>"", "active"=>"", "hoten"=>"", "phone"=>"");
        
        $ojbMUser = new MUser();
        $ojbDonHang = new DonHang();
    	if ($this->getGet['type'] == 's') {
    		$this->getPost = Session::Get("GETPOST");
    		$data = Session::Get("RESULTDONHANG");
    	} else {
    		$arrParam = array('m'=>'home', 'a'=>'donhang');
        	$data = FunctionCommon::paging($ojbDonHang, $arrParam, array(), array(), array('insert_at' => 'DESC'));
    	}
    	$arrContent = $data["data"];
		if (count ($arrContent) > 0) {
			foreach ($arrContent as $content) {
				$mUser = $ojbMUser->getOneByAttr(array('id' => $content['user_id']), array('hoten', 'phone'));
				$content['hoten'] = $mUser['hoten'];
				$content['phone'] = $mUser['phone'];
				$this->arrContent[] = $content;
			}
			$this->currPage = $data["currPage"];
			$this->numberPage = $data["numberPage"];
			$this->strPaging = $data["strPaging"];
		}
        
        // Process view
        $objView->assignobj($this);
        $objView->display();
    }
    
    /**
    * actionAjaxDonHang
    **/
    public function actionAjaxDonHang() {
    	$htmlD = "";
    	$getPost = FunctionCommon::getPost(array('maHang'));       
        $ojbDonHang = new DonHang();
        $donHang = $ojbDonHang->getOneByAttr(array('maHang' => $getPost['maHang']), array());
        if (count($donHang) > 0) {
        	$ojbMUser = new MUser();
        	$ojbGioHang = new GioHang();
        	$mUser = $ojbMUser->getOneByAttr(array('id' => $donHang['user_id']), array('hoten', 'diachi', 'tinh', 'phone', 'email'));
        	$field = "d.name as nameD, c.name as nameC, s.name as nameS, gh.soluong, gh.dongia, gh.tongtien";
        	$atrr = array('gh.maHang' => array('math'=>'=', 'value'=>$getPost['maHang']));
        	$giohangs = $ojbGioHang->getThongTinSPGioHang($atrr, $field, 'gh.insert_at');
        	$htmlD = 	"<table width='100%' border='0' align='center' cellpadding='5' cellspacing='0' bgcolor='#FFFFFF' style='font-size:12px;'>".
        				"<tr><td colspan='2' style='color: #0099FF;'>THÔNG TIN KHÁCH HÀNG</td></tr>".
			  			"<tr><th align='left' width='23%'>Họ và tên : </th><td>" . $mUser['hoten'] . "</td></tr>".
			  			"<tr><th align='left'>Địa chỉ :</th><td>" . $mUser['diachi'] . "</td></tr>".
			  			"<tr><th align='left'>Tỉnh/Thành phố :</th><td>" . constants::$arrayCountry[$mUser['tinh']] . "</td></tr>".
			  			"<tr><th align='left'>Quốc gia :</th><td>Việt Nam</td></tr>".
			  			"<tr><th align='left'>Điận thoại :</th><td>" . $mUser['phone'] . "</td></tr>".
			  			"<tr><th align='left'>E-mail :</th><td><span style='cursor:pointer;' onclick=\"hrefLocation('index.php?m=user&a=sendmail&mail=','" . $mUser['email'] . "','" . constants::$pathUrl . "')\">" . $mUser['email'] . "</span></td></tr>".
			  			"<tr><td colspan='2' style='color: #0099FF;'>PHƯƠNG THỨC THANH TOÁN</td></tr>".
			  			"<tr><th align='left'>Thanh toán qua cổng :</th><td>" . constants::$typeThanhToan[$donHang['type_tt']] . "</td></tr>".
						"<tr><td style='color: #0099FF;'>THÔNG TIN HÓA ĐƠN MÃ : </td><td style='color: #F00;font-weight:bold;'>" . $donHang['maHang'] . "</td></tr>".
			  			"<tr><td>&nbsp;</td><td>&nbsp;</td></tr>".
			  			"<tr><td colspan='2' align='center' valign='top'>".
			  			"<table width='100%' border='0' cellspacing='0' cellpadding='5'>".
			      		"<tr>".
			        	"<th align='center' class='border-top border-left'>Tên sản phẩm</th>".
			        	"<th align='center' class='border-top border-left' width='20%'>Số lượng</th>".
			        	"<th align='center' class='border-top border-left' width='20%'>Đơn giá</th>".
			        	"<th align='center' class='border-top border-left border-right' width='20%'>Thành tiền</th>".
			      		"</tr>";
			      		$tongtien = 0; 
			      		foreach ($giohangs as $gh) {
			      		$htmlD .= 	"<tr>".
			      					"<td class='border-top border-left'>" . $gh['nameD'] . (($gh['nameC'] != '') ? ' | ' . $gh['nameC'] : '') . " | " . $gh['nameS'] . "</td>".
			      					"<td align='center' class='border-top border-left'>" . $gh['soluong'] . "</td>".
			      					"<td align='center' class='border-top border-left'>" . number_format($gh['dongia']) . ".000 VNĐ</td>".
			      					"<td align='center' class='border-top border-left border-right'>" . number_format($gh['tongtien']) . ".000 VNĐ</td>".
			      					"</tr>";
			      		$tongtien += $gh['tongtien'];
			      		}
			$htmlD .= 	"<tr>".
			        	"<th colspan='3' align='right' class='border-top border-left'>Chi phí hóa đơn :</th>".
			        	"<td align='right' class='border-top border-right'>" . number_format($tongtien) . ".000 VNĐ</td>".
			      		"</tr>".
			      		"<tr>".
			        	"<th colspan='3' align='right' class='border-left'>Phí dịch vụ :</th>".
			        	"<td align='right' class='border-right'>" . number_format($donHang['phiDV']) . " VNĐ</td>".
			      		"</tr>".
			      		"<tr>".
			        	"<th colspan='3' align='right' class='border-left border-bottom'>Thành tiền :</th>".
			        	"<td align='right' class='border-right border-bottom' style='font-size:14px;color:#F00;font-weight:bold;'>" . number_format($tongtien*1000+$donHang['phiDV']) . " VNĐ</td>".
			      		"</tr>".
			    		"</table>".
			    		"</td></tr>".
						"</table>";
        }
    	echo $htmlD;
    }
    
	/**
    * actionAjaxActive
    **/
    public function actionAjaxActive() {
    	$getPost = FunctionCommon::getPost(array('maHang'));       
        $ojbDonHang = new DonHang();
        $ojbKhohang = new KhoHang();
        $ojbGioHang = new GioHang();
        $ojbSanPham = new MSanpham();
        // Update gio hang
        $getAllDonHang = $ojbDonHang->getOneByAttr(array('maHang'=>$getPost['maHang']), array());
        $idKhoHang = explode("-", $getAllDonHang['id_khohang']);
    	if (is_array($idKhoHang) && !empty($idKhoHang)) {
        	foreach ($idKhoHang as $idKH) {
        		if ($idKH != '') {
        			$ojbKhohang->setAttribute("del", "1");
        			$ojbKhohang->update(array("id" => $idKH));
        			$ojbKhohang->emptyAttribute();
        		}
        	}
       	}
    	// Update san pham
    	$getAllGioHang = $ojbGioHang->getAllByAttribute(array("maHang"=>$getPost['maHang']), array("gh_sanpham", "soluong"), array(), "id");
    	$arrSPTypeBy2 = array();
		foreach ($getAllGioHang as $ghs) {
			if ($ghs['type'] == '2') {
				$arrSPTypeBy2[$ghs['gh_sanpham']] = $ghs['soluong'];
			}
		}
		$idSanPham = explode("-", $getAllDonHang['id_sanpham']);
		if (is_array($idSanPham) && !empty($idSanPham) && count($arrSPTypeBy2) > 0) {
		  	foreach ($idSanPham as $idSP) {
		  		if ($idSP != '') {
		  			$ojbSanPham->updateSoLuong($idSP, $arrSPTypeBy2[$idSP]);
		  			$ojbSanPham->emptyAttribute();
		  		}
		  	}
		}
        
        $ojbDonHang->setAttribute("active", "1");
        $ojbDonHang->update(array("maHang" => $getPost['maHang']));
        $ojbDonHang->emptyAttribute();
        echo "1";
    }
	
	/**
    * actionSearch
    */
	public function actionSearch() {
		$objView = new ViewAdmin ();
		require_once(LIB_CORE_DIR . "/Paging.class.php");
		$objPaging = new Paging();
		$ojbDonHang = new DonHang();
		$arrParam = array('m'=>'home', 'a'=>'search');
		
		$getPost = FunctionCommon::getPost(array('maHang', 'dateStart', 'dateEnd', 'active', 'hoten', 'phone'));
		$sqlKD = "";
		if (isset($_POST['SubSearch'])) {
			if ($getPost['maHang'] != '') {
				$sqlKD .= " AND maHang like '%".$getPost['maHang']."%'";
			}
			if ($getPost['dateStart'] != '' && $getPost['dateEnd'] == '') {
				$dateStarA = explode("-", $getPost['dateStart']);
				$dateStar = $dateStarA['2'] . "-" . $dateStarA['1'] . "-" . $dateStarA['0'] . " 00:00:00";
				$sqlKD .= " AND insert_at >= '" . $dateStar . "'";
			} elseif ($getPost['dateStart'] == '' && $getPost['dateEnd'] != '') {
				$dateStarA = explode("-", $getPost['dateEnd']);
				$dateStar = $dateStarA['2'] . "-" . $dateStarA['1'] . "-" . $dateStarA['0'] . " 24:00:00";
				$sqlKD .= " AND insert_at <= '" . $dateStar . "'";
			} elseif ($getPost['dateStart'] != '' && $getPost['dateEnd'] != '') {
				$dateStarA = explode("-", $getPost['dateStart']);
				$dateStarB = explode("-", $getPost['dateEnd']);
				$dateStar1 = $dateStarA['2'] . "-" . $dateStarA['1'] . "-" . $dateStarA['0'] . " 00:00:00";
				$dateStar2 = $dateStarB['2'] . "-" . $dateStarB['1'] . "-" . $dateStarB['0'] . " 24:00:00";
				$sqlKD .= " AND insert_at >= '" . $dateStar1 . "' AND insert_at <= '" . $dateStar2 . "'";
			}
			if ($getPost['active'] != '') {
				$sqlKD .= " AND active = '" . $getPost['active'] . "'";
			}
			if ($getPost['hoten'] != '') {
				$sqlKD .= " AND user_id in (SELECT id FROM m_user WHERE hoten like '%". $getPost['hoten'] ."%')";
			}
			if ($getPost['phone'] != '') {
				$sqlKD .= " AND user_id in (SELECT id FROM m_user WHERE phone like '%". $getPost['phone'] ."%')";
			}
			
			Session::Set("sqlKD", $sqlKD);
			Session::Set("GETPOST", $getPost);
		} else {
			$sqlKD = Session::Get("sqlKD");
		}

		$sql1 = "SELECT COUNT(id) as count_data FROM donhang WHERE 1=1" . $sqlKD;
	    // Get total record of content menu
	    $rsField = $ojbDonHang->execute($sql1, ADODB_FETCH_ASSOC);
		$totalRecord = $rsField->fields['count_data'];
		 // Get page current
        if (isset($_REQUEST["pageNo"])) {
        	$currentPage = $_REQUEST["pageNo"];
        }
        else {
            $currentPage = 1;
        }
		$numberRecord = 4;
        // get page number
		if (!is_null($numberRecord) && $numberRecord != 0) {
			$numberPage = ceil($totalRecord / $numberRecord);
		} else {
			$numberPage = 0;
		}
		// get start record
		$startRecord = ($currentPage - 1) * $numberRecord;

        // get array paging
		$arrPage = $objPaging->getArrPaging($currentPage, $numberPage);
		// get string page
		$strPaging = $objPaging->getStrPaging($arrPage, $currentPage, $numberPage, $arrParam);

        // Get all content menu
        $rsField = false;
        $sql2 = "SELECT * FROM donhang WHERE 1=1" . $sqlKD . " ORDER BY insert_at DESC LIMIT " . $startRecord . ", " . $numberRecord;
        $rsField = $ojbDonHang->execute($sql2, ADODB_FETCH_ASSOC);
		$content = array();
		if($rsField) {
            while (! $rsField->EOF && $item = $rsField->FetchRow()) { 
                $content[] = $item;
            }
        }

        $no = $startRecord + 1;
		$result = array("total"=>$totalRecord,
						"data"=>$content,
						"currPage"=>$currentPage,
						"numberPage"=>$numberPage,
						"strPaging"=>$strPaging,
						"no"=>$no);
		Session::Set("RESULTDONHANG", $result);
		//FunctionCommon::sendRedirect("index.php?m=home&a=donhang&type=s".constants::$pathUrl);
		
		// Process view
        $objView->assignobj($this);
        $objView->display();
	}
}
?>

